<?php

$app_id = '260604467289805';
$app_secret = '615a0c535c0c8bb2f5001806ee271d0d';
$url = 'http://sms.matthewlittle.info';
$login_url = $url . '/login.php';
$permissions = 'email';

session_start();
setcookie(session_name(),session_id(),time() + 2592000);

$code = $_REQUEST["code"];

if(empty($code)) {
	$_SESSION['state'] = md5(uniqid(rand(), TRUE));
	$dialog_url = "http://www.facebook.com/dialog/oauth?scope=" . $permissions
		. "&client_id=" . $app_id
		. "&redirect_uri=" . urlencode($login_url)
		. "&state=". $_SESSION['state'];
	
	echo("<script> top.location.href='" . $dialog_url . "'</script>");
}

if($_REQUEST['state'] == $_SESSION['state']) {
	$token_url = "https://graph.facebook.com/oauth/access_token?"
		. "client_id=" . $app_id . "&redirect_uri=" . urlencode($login_url)
		. "&client_secret=" . $app_secret . "&code=" . $code;
	
	$response = file_get_contents($token_url);
	$params = null;
	parse_str($response, $params);
	
	$graph_url = "https://graph.facebook.com/me?access_token=" 
		. $params['access_token'];
	
	$user = json_decode(file_get_contents($graph_url));
	$_SESSION['facebookid'] = $user->id;
	$_SESSION['username'] = $user->first_name . ' ' . $user->last_name;
	$_SESSION['company'] = $user->work[0]->employer->name;
	$_SESSION['timezone'] = $user->timezone;
	$_SESSION['emailaddress'] = $user->email;
	echo("<script> top.location.href='" . $url . "'</script>");
}
else {
	echo("The state does not match. You may be a victim of CSRF.");
}


?>